//
//  KAlertView.m
//  NeiHan
//
//  Created by Kevin on 2017/4/19.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KAlertView.h"
#import "FXBlurView.h"


@interface KAlertView ()<UITextFieldDelegate>

@property(nonatomic,weak)UIView* contentView;
@property(nonatomic,weak)FXBlurView* blurView;

@property(nonatomic,weak)UILabel* titleLabel;
@property(nonatomic,weak)UILabel* contentLabel;
@property(nonatomic,weak)UITextField* textfield;

@property(nonatomic,weak)UIButton* confirmButton;
@property(nonatomic,weak)UIButton* cancelButton;

@property(nonatomic,weak)UIView* upLine;
@property(nonatomic,weak)UIView* downLine;
@property(nonatomic,weak)UIView* btnLine;

@property(nonatomic,assign)KAlertViewStyle alertStyle;
@property(nonatomic,assign)KAlertViewButtonAlignment alignment;
@property(nonatomic,copy)NSString* title;
@property(nonatomic,copy)NSString* content;
@property(nonatomic,copy)NSString* placeholder;
@property(nonatomic,copy)NSString* confirmText;
@property(nonatomic,copy)NSString* cancelText;
@end

@implementation KAlertView
-(instancetype)init{
    self = [super init];
    if (self) {
        [self settingUp];
    }
    return self;
}
-(instancetype)initWithTitle:(NSString *)title content:(NSString *)content placeholder:(NSString *)placeholder style:(KAlertViewStyle)style confirmTitle:(NSString *)confirmTitle cancelTitle:(NSString *)cancelTitle{
    if (self == [super init]) {
        _title = title ? : @"";
        _content = content ? : @"";
        _placeholder = placeholder ? : @"请输入文字";
        _alertStyle = style;
        _alignment = KAlertViewButtonAlignmentHorizontal;
        _confirmText = confirmTitle?:@"确定";
        _cancelText = cancelTitle?:@"取消";
        [self settingUp];
    }
    return self;
}

-(instancetype)initWithTitle:(NSString*)title content:(NSString*)content placeholder:(NSString*)placeholder style:(KAlertViewStyle)style{
    if (self == [super init]) {
        _title = title ? : @"";
        _content = content ? : @"";
        _placeholder = placeholder ? : @"请输入文字";
        _alertStyle = style;
        _alignment = KAlertViewButtonAlignmentHorizontal;
        _confirmText = @"确定";
        _cancelText = @"取消";
        [self settingUp];
    }
    return self;
}

-(instancetype)initWithTitle:(NSString *)title content:(NSString *)content placeholder:(NSString *)placeholder style:(KAlertViewStyle)style alignment:(KAlertViewButtonAlignment)alignment confirmTitle:(NSString *)confirmTitle cancelTitle:(NSString *)cancelTitle
{
    if (self == [super init]) {
        _title = title ? : @"";
        _content = content ? : @"";
        _placeholder = placeholder ? : @"请输入文字";
        _alertStyle = style;
        _alignment = alignment;
        _confirmText = confirmTitle?:@"确定";
        _cancelText = cancelTitle?:@"取消";
        [self settingUp];
    }
    return self;
}

-(void)settingUp{
    self.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4f];
    
    if (_title.length > 1) {
        NSMutableAttributedString* attributeTitle = [[NSMutableAttributedString alloc]initWithString:_title];
        NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc]init];
        paragraph.lineSpacing = 3.0;
        paragraph.alignment = NSTextAlignmentCenter;
        [attributeTitle addAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor],NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraph} range:NSMakeRange(0, attributeTitle.length)];
        self.titleLabel.hidden = NO;
        self.upLine.hidden = NO;
        self.titleLabel.attributedText = attributeTitle;
    }
    
    if (_content.length > 1) {
        NSMutableAttributedString* attributeContent = [[NSMutableAttributedString alloc]initWithString:_content];
        NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc]init];
        paragraph.alignment = NSTextAlignmentCenter;
        paragraph.lineSpacing = 5.0;
        [attributeContent addAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor],NSFontAttributeName:[UIFont systemFontOfSize:[UIFont systemFontSize]],NSParagraphStyleAttributeName:paragraph} range:NSMakeRange(0, attributeContent.length)];
        self.contentLabel.attributedText = attributeContent;
    }
    [self.confirmButton setTitle:_confirmText forState:UIControlStateNormal];
    
    if (self.alertStyle == KAlertViewTextInput) {
        self.textfield.placeholder = self.placeholder;
        if ([self.placeholder containsString:@"密码"]) {
            self.textfield.secureTextEntry = YES;
        }else{
            self.textfield.secureTextEntry = NO;
        }
        self.textfield.hidden = NO;
        self.btnLine.hidden = NO;
        self.cancelButton.hidden = NO;
        [self.cancelButton setTitle:_cancelText forState:UIControlStateNormal];
    }else if (self.alertStyle == KAlertViewTip){
        self.btnLine.hidden = YES;
    }else if (self.alertStyle == KAlertViewAlert){
        self.cancelButton.hidden = NO;
        [self.cancelButton setTitle:_cancelText forState:UIControlStateNormal];
        self.btnLine.hidden = NO;
    }
    
    if (_alignment == KAlertViewButtonAlignmentVertical) {
        [self.confirmButton setBackgroundImage:[UIImage imageNamed:@"button_back"] forState:UIControlStateNormal];
        [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.confirmButton.layer.cornerRadius = 20.0;
        
        self.cancelButton.layer.cornerRadius = 20.0;
        self.cancelButton.layer.borderWidth = 0.3;
        self.cancelButton.layer.borderColor = [UIColor grayColor].CGColor;
    }
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    [self.contentView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width*0.7, 150)];
    if (_title.length > 1) {
        CGFloat titleH = [self heightWithAttributedString:self.titleLabel.attributedText inw:self.contentView.width-20];
        self.titleLabel.frame = CGRectMake(10, 10, self.contentView.width-20, titleH);
        self.upLine.frame = CGRectMake(0, self.titleLabel.bottom+7, self.contentView.width, 1);
    }else{
        self.titleLabel.frame = CGRectMake(0, 0, 0, 0);
        self.upLine.frame = CGRectMake(0, 0, 0, 0);
    }
    
    if (_content.length > 1) {
        CGFloat contentH = [self heightWithAttributedString:self.contentLabel.attributedText inw:self.contentView.width-30];
        self.contentLabel.frame = CGRectMake(15, self.upLine.bottom+15, self.contentView.width-30, contentH);
    }else{
        self.contentLabel.frame = CGRectMake(0, self.upLine.bottom, 0, 0);
    }
    if (_alignment == KAlertViewButtonAlignmentHorizontal) {
        if (self.alertStyle == KAlertViewTip) {
            self.downLine.frame = CGRectMake(0, self.contentLabel.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(0, self.downLine.bottom, self.contentView.width, 40);
        }else if (self.alertStyle == KAlertViewAlert){
            self.downLine.frame = CGRectMake(0, self.contentLabel.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(0, self.downLine.bottom, self.contentView.width/2-0.5, 40);
            self.btnLine.frame = CGRectMake(self.confirmButton.right, self.downLine.bottom, 1, 40);
            self.cancelButton.frame = CGRectMake(self.btnLine.right, self.downLine.bottom, self.contentView.width/2-0.5, 40);
        }else if (self.alertStyle == KAlertViewTextInput){
            self.textfield.frame = CGRectMake(15, self.contentLabel.bottom+15, self.contentView.width-30, 32);
            self.downLine.frame = CGRectMake(0, self.textfield.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(0, self.downLine.bottom, self.contentView.width/2-0.5, 40);
            self.btnLine.frame = CGRectMake(self.confirmButton.right, self.downLine.bottom, 1, 40);
            self.cancelButton.frame = CGRectMake(self.btnLine.right, self.downLine.bottom, self.contentView.width/2-0.5, 40);
        }
        self.contentView.height = self.confirmButton.bottom;
    }else{
        if (self.alertStyle == KAlertViewTip) {
            self.downLine.frame = CGRectMake(0, self.contentLabel.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(0, self.downLine.bottom, self.contentView.width, 40);
            self.contentView.height = self.confirmButton.bottom+5;
        }else if (self.alertStyle == KAlertViewAlert){
            self.downLine.frame = CGRectMake(0, self.contentLabel.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(10, self.downLine.bottom, self.contentView.width - 20, 40);
            self.btnLine.frame = CGRectMake(self.confirmButton.right, self.downLine.bottom, 0, 40);
            self.cancelButton.frame = CGRectMake(10, self.confirmButton.bottom+5, self.contentView.width-20, 40);
            self.contentView.height = self.cancelButton.bottom+5;
        }else if (self.alertStyle == KAlertViewTextInput){
            self.textfield.frame = CGRectMake(15, self.contentLabel.bottom+15, self.contentView.width-30, 32);
            self.downLine.frame = CGRectMake(0, self.textfield.bottom+15, self.contentView.width, 1);
            self.confirmButton.frame = CGRectMake(10, self.downLine.bottom, self.contentView.width-20, 40);
            self.btnLine.frame = CGRectMake(self.confirmButton.right, self.downLine.bottom, 0, 40);
            self.cancelButton.frame = CGRectMake(10, self.confirmButton.bottom+5, self.contentView.width-20, 40);
            self.contentView.height = self.cancelButton.bottom+5;
        }
    }

    
    self.contentView.center = self.center;
}


#pragma mark - Actions
+(BOOL)isAlertViewShowingInView:(UIView*)view{
    if (view == nil) view = [UIApplication sharedApplication].keyWindow;
    UIView* alert = [view viewWithTag:910808];
    return alert != nil;
}

-(void)setClickBlock:(void (^)(BOOL, NSString *))ClickBlock{
    _ClickBlock = ClickBlock;
}

-(CGFloat)heightWithAttributedString:(NSAttributedString*)string inw:(CGFloat)w{
    return [string boundingRectWithSize:CGSizeMake(w, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height+3;
}

-(void)confirmAction{
    if (self.ClickBlock) {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [self.blurView clearImage];
                [self.blurView removeFromSuperview];
                if (self.ClickBlock) {
                    self.ClickBlock(1,self.textfield.text);
                }
            }
        }];
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [self.blurView clearImage];
                [self.blurView removeFromSuperview];
            }
        }];
    }
}
-(void)cancelAction{
    if (!self.ClickBlock) {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [self.blurView clearImage];
                [self.blurView removeFromSuperview];
            }
        }];
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [self.blurView clearImage];
                [self.blurView removeFromSuperview];
                if (self.ClickBlock) {
                    self.ClickBlock(0,self.textfield.text?:@"");
                }
            }
        }];
    }
}

-(void)showInView:(UIView *)view{
    
    BOOL isShowing = [KAlertView isAlertViewShowingInView:view];
    if (isShowing) return ;
    
    UIView *content = view ? view  : [UIApplication sharedApplication].keyWindow;
    self.blurView.blurRadius = 0;
    self.frame = content.bounds;
    self.alpha = 0;
    self.tag = 910808;
    
    [content addSubview:self.blurView];
    [content addSubview:self];
    
    
    [UIView animateWithDuration:0.35 animations:^{
        self.alpha = 1;
        self.blurView.blurRadius = 12.0f;
    } completion:^(BOOL finished) {
        self.blurView.dynamic = NO;
        [FXBlurView setUpdatesDisabled];
    }];
}

#pragma mark - LazyLoad
-(UIView *)upLine{
    if (!_upLine) {
        UIView* line = [[UIView alloc]init];
        line.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0];
        line.hidden = YES;
        [self.contentView addSubview:line];
        _upLine = line;
    }
    return _upLine;
}
-(UIView *)downLine{
    if (!_downLine) {
        UIView* line = [[UIView alloc]init];
        line.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0];
        [self.contentView addSubview:line];
        _downLine = line;
    }
    return _downLine;
}

-(UIView *)btnLine{
    if (!_btnLine) {
        UIView* line = [[UIView alloc]init];
        line.hidden = YES;
        line.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0];
        [self.contentView addSubview:line];
        _btnLine = line;
    }
    return _btnLine;
}

-(UIView *)contentView{
    if (!_contentView) {
        UIView* content = [[UIView alloc]init];
        content.layer.cornerRadius = 5.0f;
        content.backgroundColor = [UIColor whiteColor];
        [self addSubview:content];
        _contentView = content;
    }
    return _contentView;
}

-(FXBlurView *)blurView{
    if (!_blurView) {
        FXBlurView* blur = [[FXBlurView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        blur.tintColor = [UIColor clearColor];
        blur.blurRadius = 0;
        _blurView = blur;
    }
    return _blurView;
}

-(UIButton *)confirmButton{
    if (!_confirmButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:[UIColor colorWithRed:18/255.0 green:121/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
        button.clipsToBounds = YES;
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
        _confirmButton = button;
    }
    return _confirmButton;
}

-(UIButton *)cancelButton{
    if (!_cancelButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:[UIColor colorWithRed:18/255.0 green:121/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        button.hidden = YES;
        [button addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
        _cancelButton = button;
    }
    return _cancelButton;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        UILabel* lb = [[UILabel alloc]init];
        lb.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
        lb.hidden = YES;
        lb.numberOfLines = 0;
        lb.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:lb];
        _titleLabel = lb;
    }
    return _titleLabel;
}
-(UILabel *)contentLabel{
    if (!_contentLabel) {
        UILabel* lb = [[UILabel alloc]init];
        lb.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        lb.numberOfLines = 0;
        lb.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:lb];
        _contentLabel = lb;
    }
    return _contentLabel;
}

-(UITextField *)textfield{
    if (!_textfield) {
        UITextField* tf = [[UITextField alloc]init];
        tf.borderStyle = UITextBorderStyleNone;
        tf.delegate = self;
        tf.hidden = YES;
        tf.layer.cornerRadius = 5.0;
        tf.layer.borderWidth = 1.0f;
        tf.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        tf.layer.borderColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0].CGColor;
        tf.returnKeyType = UIReturnKeyDone;
        [self.contentView addSubview:tf];
        _textfield = tf;
    }
    return _textfield;
}

@end
